import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "nprogress";
import { useUserStore } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import "nprogress/nprogress.css";

const Layout = () => import("@/layout/index.vue");

const routes = [
  {
    path: "/",
    component: Layout,
    redirect: "/selected",
    children: [
      {
        path: "/selected",
        name: "Selected",
        component: () => import("@/view/Selected/index.vue"),
        meta: {
          title: "精选",
        },
      },
      {
        path: "/recommend",
        name: "Recommend",
        component: () => import("@/view/Recommend/index.vue"),
        meta: {
          title: "推荐",
        },
      },
      {
        path: "/mine",
        name: "Mine",
        component: () => import("@/view/Mine/index.vue"),
        meta: {
          title: "我的",
          requiresAuth: true,
        },
      },
      // 添加用户中心路由，用于查看他人的资料
      {
        path: "/user/:userId",
        name: "UserProfile",
        component: () => import("@/view/Mine/index.vue"),
        meta: {
          title: "用户中心",
        },
        props: true, // 将路由参数作为props传给组件
      },
      {
        path: "/creation",
        name: "Creation",
        component: () => import("@/view/Creation/index.vue"),
        meta: {
          title: "创作",
          requiresAuth: true,
        },
      },
    ],
  },
  // 添加搜索路由
  {
    path: "/search",
    name: "Search",
    component: () => import("@/view/Search/index.vue"),
    meta: {
      title: "搜索",
      requiresAuth: true,
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 设置路由前置守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();

  const userStore = useUserStore();
  const requiresAuth = to.meta.requiresAuth || false;

  // 检查是否已登录（此检查会验证 token 是否有效）
  const isLogin = userStore.isLoggedIn();

  // 检查路由是否需要登录权限
  if (requiresAuth && !isLogin) {
    // 用户未登录，显示提示并打开登录弹窗
    ElMessage.warning("请先登录");
    userStore.openAuthModal("login");

    // 重定向到首页或其他允许访问的页面
    next({ path: "/selected" });
  } else {
    // 允许访问
    next();
  }
});

// 设置路由后置守卫
router.afterEach((to) => {
  NProgress.done();
});

// 对外暴露路由器
export default router;
